package com.user.service.Impl;

import DO.user.CityDO;
import DO.user.ProvincialDO;
import Exception.IDIsNotRightException;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.user.mapper.CityMapper;
import com.user.service.CityService;
import constant.RedisPreKeyConstant;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class CityServiceImpl implements CityService {

    @Autowired
    private CityMapper cityMapper;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    // 获取一级地名
    public List<ProvincialDO> getFirstCity() {

        List<ProvincialDO> firstCity;

        // 1. 第一步，判断redis中有无数据，如果有数据直接返回
        String firstCityString = stringRedisTemplate.opsForValue().get(RedisPreKeyConstant.CITY_FIRST);
        if (firstCityString!=null){
            // redis 中有数据，将这个对象转化为字符串将其存入redis中
            firstCity = JSON.parseObject(firstCityString, new TypeReference<List<ProvincialDO>>(){});
        }
        else {
            // redis中无数据，从数据库中查询对象，然后将其存入redis中
            firstCity = cityMapper.getFirstCity();
            stringRedisTemplate.opsForValue().set(RedisPreKeyConstant.CITY_FIRST,JSON.toJSONString(firstCity));
        }
        return firstCity;
    }



    // 获取二级标题
    public List<CityDO> getSecondCity(Integer id) {
        List<CityDO> secondCity;
        String secondCityString = stringRedisTemplate.opsForValue().get(RedisPreKeyConstant.CITY_SECOND + id);
        if (secondCityString!=null){
            // 表示redis中有数据
            secondCity = JSON.parseObject(secondCityString,new TypeReference<List<CityDO>>(){});
        }else {
            secondCity = cityMapper.getSecondCity(id);
            if (secondCity.isEmpty()){
                // 表示这个id是错误的 code = 105
                throw new IDIsNotRightException();
            }
            // 将这个存入redis中
            stringRedisTemplate.opsForValue().set(RedisPreKeyConstant.CITY_SECOND+id,JSON.toJSONString(secondCity));
        }

        return secondCity;
    }
}
